<template>
  <div class="bgc-default pad-20">
    <div class="bg-color-white pad-20">
      <div>
        <el-button type="primary" @click="addWholesalerGrade()">新增</el-button>
      </div>
      <!-- 内容列表 -->
      <div class="table-container">
        <el-table ref="multipleTable" :data="entityList" v-loading="listLoading" element-loading-text="加载中" style="width: 100%">
          <el-table-column label="等级值" prop="gradeValue"></el-table-column>
          <el-table-column label="等级名称" prop="gradeName">
            <template  slot-scope="scope">
              <el-input class="width-150" maxlength="32" size="mini" v-if="scope.row.isEdit" v-model="entity.gradeName"></el-input>
              <div v-else>{{scope.row.gradeName}}</div>
            </template>
          </el-table-column>
          <el-table-column label="升级规则" prop="upgradeRules">
          </el-table-column>
          <el-table-column label="查看商品权限" prop="goodsAuthority">
            <template slot-scope="scope">
              <div class="flex-col" v-if="scope.row.isEdit">
                <div>
                  <el-radio v-model="entity.goodsAuthority" label="1">可见全部商品</el-radio>
                </div>
                <div class="flex">
                  <el-radio v-model="entity.goodsAuthority" label="2">部分商品不可见</el-radio>
                  <el-select placeholder="请选择" clearable filterable v-model="entity.goodsGroupIds" v-if="entity.goodsAuthority === '2'">
                    <el-option v-for="item in goodsGroupList" :key="item.goodsGroupId" :label="item.goodsGroupName"
                      :value="item.goodsGroupId">
                    </el-option>
                  </el-select>
                </div>
              </div>
              <div v-else>
                <div v-if="scope.row.goodsAuthority === 1">可见全部商品</div>
                <div v-if="scope.row.goodsAuthority === 2">部分商品不可见</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="批发商数" prop="wholesalerNum">
            <template slot-scope="scope">
              {{ countGradeWholesalerMap[scope.row.gradeValue] ? countGradeWholesalerMap[scope.row.gradeValue] : 0 }}
            </template>
          </el-table-column>
          <el-table-column width="140px" label="操作" align="right" fixed="right">
            <template slot-scope="scope">
              <div v-if="scope.row.isEdit">
                <el-button type="text" @click="saveEntity(scope.row)">确定</el-button>
                <el-button type="text" @click="cancelEntity(scope.row)">取消</el-button>
              </div>
              <div v-else>
                <el-button type="text" @click="detailGrateWholesaler(scope.row)">查看批发商</el-button>
                <el-button type="text" @click="editEntity(scope.row)">编辑</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 列表分页 -->
      <div class="pagination">
        <el-pagination background @size-change="handleSizeChange"
                       @current-change="handleCurrentChange" :current-page="entityListQuery.currentPage"
                       :page-sizes="[10, 20, 50, 100]" :page-size="entityListQuery.size" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
  import { pageWholesalerGrade, saveWholesalerGrade } from '@/api/user/memberGrade'
  import { statisticsByWholesalerGrade } from '@/api/user/memberRoleAuthority'
  import { listGoodsGroup } from '@/api/goods/goodsGroup'
  export default {
    data() {
      return {
        // 列表数据
        entityList: [],
        // 商品组列表
        goodsGroupList: [],
        total: null,
        // 查询条件
        entityListQuery: {
          currentPage: 1,
          size: 10,
          enterpriseId: this.getEnterpriseId()
        },
        listLoading: false,
        isAdd: true,
        entity: {
          enterpriseId: this.getEnterpriseId(),
          gradeId: '',
          gradeName: '',
          upgradeRules: '',
          goodsAuthority: '',
          goodsGroupIds: ''
        },
        countGradeWholesalerMap: {}
      }
    },
    created() {
      this.initPage()
      this.getGoodsGroupList()
      this.countWholesaler()
    },
    methods: {
      // 统计每个等级的批发商
      countWholesaler() {
        statisticsByWholesalerGrade(this.getEnterpriseId()).then(response => {
          if (response.isError) return
          const countWholesalerList = response.data
          const countMap = {}
          countWholesalerList.forEach(e => {
            countMap[e.gradeValue] = e.gradeWholesalerCount
          })
          this.countGradeWholesalerMap = countMap
        })
      },
      // 获取批发商品组集合
      getGoodsGroupList() {
        listGoodsGroup({ enterpriseId: this.getEnterpriseId(), groupType: 2 }).then(response => {
          if (response.isError) return
          this.goodsGroupList = response.data
        })
      },
      // 编辑
      editEntity(row) {
        if (!this.isAdd) {
          this.$message({
            message: '请先保存',
            type: 'error'
          })
          return
        }
        this.isAdd = false
        row.isEdit = true
        this.entity.enterpriseId = this.getEnterpriseId()
        this.entity.gradeId = row.gradeId
        this.entity.gradeValue = row.gradeValue
        this.entity.gradeName = row.gradeName
        this.entity.upgradeRules = row.upgradeRules
        this.entity.oldOrNew = 0
        this.entity.goodsAuthority = row.goodsAuthority + ''
        this.entity.goodsGroupIds = ''
        if (row.goodsAuthority === 2) {
          this.entity.goodsGroupIds = row.goodsGroupIds
        }
      },
      // 取消添加
      cancelEntity(row) {
        if (row && row.oldOrNew === 1) {
          this.entityList = this.entityList.filter((grade, idx) => idx !== (this.entityList.length - 1))
        } else {
          row.isEdit = false
        }
        this.isAdd = true
      },
      // 保存等级
      saveEntity(row) {
        const that = this
        const gradeId = that.entity.gradeId
        const gradeValue = that.entity.gradeValue
        if (!gradeValue || gradeValue > 10) {
          that.$message({
            message: '最高等级不能超过10级',
            type: 'error'
          })
          return
        }
        const gradeName = that.entity.gradeName
        if (!gradeName) {
          that.$message({
            message: '等级名称不能为空',
            type: 'error'
          })
          return
        }
        if (gradeName.length > 32) {
          that.$message({
            message: '等级名称最多输入32个字符',
            type: 'error'
          })
          return
        }
        const upgradeRules = that.entity.upgradeRules
        if (upgradeRules && upgradeRules.length > 300) {
          that.$message({
            message: '升级规则最多输入300个字符',
            type: 'error'
          })
          return
        }
        const goodsAuthority = that.entity.goodsAuthority
        const goodsGroupIds = that.entity.goodsGroupIds
        if (goodsAuthority === '2' && !goodsGroupIds) {
          that.$message({
            message: '请选择商品组',
            type: 'error'
          })
          return
        }
        that.entity = {
          enterpriseId: that.getEnterpriseId(),
          gradeId: gradeId,
          gradeValue: gradeValue,
          gradeName: gradeName,
          upgradeRules: upgradeRules,
          goodsAuthority: goodsAuthority,
          goodsGroupIds: goodsGroupIds
        }
        if (that.entity.oldOrNew === 1) {
          that.isAdd = true
        }
        saveWholesalerGrade(that.entity).then(response => {
          if (response.isError) return
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          that.isAdd = true
          this.initPage()
        })
      },
      // 移出数组元素
      removeByValue(arr, val) {
        for (var i = 0; i < arr.length; i++) {
          if (arr[i] === val) {
            arr.splice(i, 1)
            break
          }
        }
      },
      // 添加等级
      addWholesalerGrade() {
        const that = this
        var gradeArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        that.entityList.forEach(e => {
          that.removeByValue(gradeArray, e.gradeValue)
        })
        const initGradeValue = gradeArray[0]
        if (!initGradeValue) {
          this.$message({
            message: '最多只能有10个等级!',
            type: 'error'
          })
          return
        }
        if (!that.isAdd) {
          this.$message({
            message: '请先保存!',
            type: 'error'
          })
          return
        }
        that.isAdd = false
        const entity = {
          gradeId: '',
          gradeValue: initGradeValue,
          isEdit: true,
          gradeName: '等级' + initGradeValue,
          upgradeRules: '/',
          goodsAuthority: '1',
          oldOrNew: 1 // 1:新加的数据，0:旧数据
        }
        that.entityList.push(entity)
        this.entity.enterpriseId = this.getEnterpriseId()
        this.entity.gradeId = entity.gradeId
        this.entity.gradeValue = entity.gradeValue
        this.entity.gradeName = entity.gradeName
        this.entity.upgradeRules = entity.upgradeRules
        this.entity.oldOrNew = 0
        this.entity.goodsAuthority = entity.goodsAuthority
        this.entity.goodsGroupIds = ''
  
        // this.editEntity(entity)
      },
      // 加载表格数据
      initPage() {
        this.listLoading = true
        pageWholesalerGrade(this.entityListQuery).then(response => {
          if (response.isError) return
          this.entityList = response.data.records
          this.entityList.forEach(e => {
            this.$set(e, 'isEdit', false)
            this.$set(e, 'oldOrNew', 0)
          })
          this.total = response.data.total
          this.listLoading = false
        })
      },
      detailGrateWholesaler(row) {
        this.$router.push({ path: '/user/member-wholesale/index', query: { gradeValue: row.gradeValue }})
      },
      // 更改当前页数
      handleCurrentChange(val) {
        this.entityListQuery.currentPage = val
        this.initPage()
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.entityListQuery.size = val
        this.initPage()
      },
      // 勾选
      handleSelectionChange(val) {
        this.multipleSelection = val
      }
    }
  }
</script>

<style>
  .user-avatar {
    width: 68px;
    height: 68px;
    display: block;
    padding: 1px;
    border: #efefef 1px solid;
  }
</style>